<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import logger from '@/utils/logger'
import { fetchGoodsReturnList } from '@/api/goodsReturnApi'
import { formatDateTime, getNowDateTime } from '@/utils/dayjs'
import GoodReturnAuditDialog from './components/GoodReturnAuditDialog.vue'

// 列表 & 分页
const tableData = ref([])
const loading = ref(false)
const total = ref(0)

// 审核弹窗相关
const auditDialogVisible = ref(false)
const currentReturnItem = ref(null)

// 审核表单
const auditForm = ref({
  checkTime: '',
  returnPoints: 0,
  returnMoney: 0,
  checkUserId: '',
  approved: true, // 是否通过审核
})

// 请求参数
const requestParams = ref({
  currentPage: 1,
  pageSize: 10,
  queryFields: {
    returnGoodsId: '',
    orderNo: '',
    goodsName: '',
    returnReason: '',
    returnType: null, // 退货类型
    memberOrderMId: '',
    dealerGoodsId: '',
    xzqhName: '',
    dealerGoodsTypeName: '',
  },
})

// 退货类型选项
const returnTypeOptions = [
  { label: '质量问题', value: 1 },
  { label: '不满意', value: 2 },
  { label: '商品损坏', value: 3 },
  { label: '其他原因', value: 4 },
]

// 获取退货列表数据
const fetchReturnData = async () => {
  try {
    loading.value = true
    const params = {
      ...requestParams.value,
      queryFields: {
        returnGoodsId: requestParams.value.queryFields.returnGoodsId?.trim() || null,
        orderNo: requestParams.value.queryFields.orderNo?.trim() || null,
        goodsName: requestParams.value.queryFields.goodsName?.trim() || null,
        returnReason: requestParams.value.queryFields.returnReason?.trim() || null,
        returnType: requestParams.value.queryFields.returnType,
        memberOrderMId: requestParams.value.queryFields.memberOrderMId?.trim() || null,
        dealerGoodsId: requestParams.value.queryFields.dealerGoodsId?.trim() || null,
        xzqhName: requestParams.value.queryFields.xzqhName?.trim() || null,
        dealerGoodsTypeName: requestParams.value.queryFields.dealerGoodsTypeName?.trim() || null,
      },
    }
    const res = await fetchGoodsReturnList(params)
    if (res.success && res.data) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      tableData.value = []
      total.value = 0
      ElMessage.error(res.msg || '获取退货商品列表失败')
    }
  } catch (error) {
    logger.error('获取退货商品列表失败', error)
    ElMessage.error('获取退货商品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  requestParams.value.currentPage = 1
  fetchReturnData()
}

// 重置
const resetSearch = () => {
  requestParams.value.queryFields = {
    returnGoodsId: '',
    orderNo: '',
    goodsName: '',
    returnReason: '',
    returnType: null,
    memberOrderMId: '',
    dealerGoodsId: '',
    xzqhName: '',
    dealerGoodsTypeName: '',
  }
  requestParams.value.currentPage = 1
  fetchReturnData()
}

// 分页事件
const handleSizeChange = (val) => {
  requestParams.value.pageSize = val
  requestParams.value.currentPage = 1
  fetchReturnData()
}

const handleCurrentChange = (val) => {
  requestParams.value.currentPage = val
  fetchReturnData()
}

// 获取退货类型文本
const getReturnTypeText = (type) => {
  const option = returnTypeOptions.find((item) => item.value === type)
  return option ? option.label : '未知类型'
}

// 打开审核弹窗
const handleAudit = (row) => {
  currentReturnItem.value = { ...row }
  auditForm.value = {
    checkTime: getNowDateTime(),
    returnPoints: row.canReturnPoints || 0,
    returnMoney: row.amount || 0,
    checkUserId: '', // 这里应该从用户信息中获取
    approved: true,
  }
  auditDialogVisible.value = true
}

// 关闭审核弹窗
const closeAuditDialog = () => {
  auditDialogVisible.value = false
  currentReturnItem.value = null
  auditForm.value = {
    checkTime: '',
    returnPoints: 0,
    returnMoney: 0,
    checkUserId: '',
    approved: true,
  }
}

const handleAuditSubmitted = () => {
  fetchReturnData()
}

// 组件挂载
onMounted(() => {
  fetchReturnData()
})
</script>

<template>
  <GoodReturnAuditDialog
    v-model="auditDialogVisible"
    :form="auditForm"
    :current-item="currentReturnItem"
    :return-type-options="returnTypeOptions"
    @close="closeAuditDialog"
    @submitted="handleAuditSubmitted"
  />

  <div class="main-container">
    <!-- 搜索条件 -->
    <div class="controller-container">
      <div class="controller-item">
        <el-form :inline="true" :model="requestParams.queryFields" @submit.prevent="handleSearch">
          <el-form-item label="订单号">
            <el-input
              v-model="requestParams.queryFields.orderNo"
              placeholder="请输入订单号"
              clearable
              style="width: 180px"
              @keyup.enter="handleSearch"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input
              v-model="requestParams.queryFields.goodsName"
              placeholder="请输入商品名称"
              clearable
              style="width: 180px"
              @keyup.enter="handleSearch"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="退货原因">
            <el-input
              v-model="requestParams.queryFields.returnReason"
              placeholder="请输入退货原因"
              clearable
              style="width: 180px"
              @keyup.enter="handleSearch"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="退货类型">
            <el-select
              v-model="requestParams.queryFields.returnType"
              placeholder="请选择退货类型"
              clearable
              style="width: 150px"
            >
              <el-option
                v-for="option in returnTypeOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="专属区域">
            <el-input
              v-model="requestParams.queryFields.xzqhName"
              placeholder="请输入专属区域"
              clearable
              style="width: 150px"
              @keyup.enter="handleSearch"
            >
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <template #icon>
                <el-icon><LineMdSearch /></el-icon>
              </template>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <template #icon>
                <el-icon><LineMdClose /></el-icon>
              </template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table v-loading="loading" :data="tableData" style="width: 100%" height="100%">
        <el-table-column prop="orderNo" label="订单号" min-width="180" align="center" />
        <el-table-column label="商品图片" width="100" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.goodsPicture"
              :src="row.goodsPicture"
              style="width: 60px; height: 60px; border-radius: 4px"
              :preview-src-list="[row.goodsPicture]"
              fit="cover"
              preview-teleported
            />
            <div v-else class="no-image">无图片</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsName"
          label="商品名称"
          min-width="200"
          :show-overflow-tooltip="true"
          align="center"
        />
        <el-table-column prop="specifications" label="规格" min-width="120" align="center" />
        <el-table-column prop="unit" label="单位" min-width="80" align="center" />
        <el-table-column prop="purchaseQuantity" label="购买数量" min-width="100" align="center" />
        <el-table-column prop="returnQuantity" label="退货数量" min-width="100" align="center" />
        <el-table-column prop="returnType" label="退货类型" min-width="120" align="center">
          <template #default="{ row }">
            {{ getReturnTypeText(row.returnType) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="returnReason"
          label="退货原因"
          min-width="150"
          :show-overflow-tooltip="true"
          align="center"
        />
        <el-table-column prop="returnTime" label="申请时间" min-width="160" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.returnTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="canReturnpoints"
          label="可退金额（元）"
          min-width="100"
          align="center"
        />
        <el-table-column prop="xzqhName" label="专属区域" min-width="120" align="center" />
        <el-table-column prop="checkTime" label="审核时间" min-width="160" align="center">
          <template #default="{ row }">
            {{ row.checkTime ? formatDateTime(row.checkTime) : '未审核' }}
          </template>
        </el-table-column>
        <el-table-column label="审核状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.checkTime ? 'success' : 'warning'">
              {{ row.checkTime ? '已审核' : '待审核' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template #default="{ row }">
            <el-button v-if="!row.checkTime" type="primary" size="small" @click="handleAudit(row)">
              退款详情
            </el-button>
            <el-tag v-else type="info" size="small">已审核</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="requestParams.currentPage"
          v-model:page-size="requestParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.main-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;

  .controller-container {
    border-radius: 10px;
    background-color: #fff;

    .controller-item {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }

  .table-container {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 10px;
    padding: 10px;
    overflow: hidden;
    gap: 10px;

    .el-table {
      flex: 1;
    }

    .no-image {
      width: 60px;
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #909399;
      background-color: #f5f7fa;
      font-size: 12px;
      border-radius: 4px;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
